package com.nanfang51g3.ckz.ui.person;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.application.CkzApplication;
import com.nanfang51g3.ckz.event.AvatarEvent;
import com.nanfang51g3.ckz.event.InfoUpEvent;
import com.nanfang51g3.ckz.event.RxBus;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.ui.base.Base2Activity;
import com.nanfang51g3.ckz.ui.home.HomeMainActivity;
import com.nanfang51g3.ckz.ui.update.info.InfoUpActivity;
import com.nanfang51g3.ckz.utils.AppManager;
import com.nanfang51g3.ckz.utils.EasyToast;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.SPUtil;
import com.nanfang51g3.ckz.utils.ToolUtils;
import com.nanfang51g3.ckz.widget.GlideCircleTransform;
import com.nanfang51g3.ckz.widget.pics.CropHandler;
import com.nanfang51g3.ckz.widget.pics.CropHelper;
import com.nanfang51g3.ckz.widget.pics.CropParams;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Administrator on 2016/4/19.
 */
public class PersonActivity extends Base2Activity implements PersonContract.View, CropHandler {
    PersonContract.PersonActionsListener personActionsListener;
    @Bind(R.id.iv_person_avatar)
    ImageView ivPersonAvatar;
    @Bind(R.id.tv_person_name)
    TextView tvPersonName;
    @Bind(R.id.tv_person_email)
    TextView tvPersonEmail;
    @Bind(R.id.tv_person_qq)
    TextView tvPersonQq;
    @Bind(R.id.tv_person_phone)
    TextView tvPersonPhone;
    Subscription rxSubscription;
    @Override
    public IPresenter getPresenter() {
        return null;
    }
    private CropParams mCropParams;

    @Override
    public int getContentView() {
        return R.layout.person;
    }

    @Override
    public boolean isShowLeftIcon() {
        return true;
    }

    @Override
    public boolean isShowRightIcon() {
        return false;
    }

    @Override
    public int setLeftIcon() {
        return R.mipmap.ic_accounting_left;
    }

    @Override
    public int setRightIcon() {
        return 0;
    }

    @Override
    public int showTitle() {
        return R.string.str_person;
    }

    @Override
    public void onClickLeft(View v) {
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    public void onClickRight(View v) {

    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void showUi(String userPic, String userName, String email, String qq, String phone) {
        KLog.i("Evd", "userName=" + userName + "-" + ToolUtils.isZN(userName));
        String cont = "cKTcKT_";
        if (userName.contains(cont)) {
            tvPersonName.setText("请填写昵称");
        } else {
            tvPersonName.setText(userName);
        }


        tvPersonEmail.setText(email);
        tvPersonQq.setText(qq);
        tvPersonPhone.setText(phone);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String userpic = (String) SPUtil.get(this, "userpic", "");
        Glide.with(this).load(userpic).placeholder(R.mipmap.ic_default_avatar).transform(
                new GlideCircleTransform(this)
        ).into(ivPersonAvatar);
    }

    @Override
    public void showMessage(String message) {
        EasyToast.showShort(this, message);
    }

    @Override
    public void showAvatar(File file) {
        Glide.with(this).load(file).placeholder(R.mipmap.ic_default_avatar).transform(
                new GlideCircleTransform(this)
        ).into(ivPersonAvatar);
        //发送
        RxBus.getDefault().post(new AvatarEvent(file));
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        personActionsListener = DaggerPersonContractComponent
                .builder()
                .appComponent(CkzApplication.getAppComponent())
                .personPresenterModule(new PersonPresenterModule(this))
                .build().getPersonPresenter();
        Log.i("TAG", personActionsListener == null ? "personActionsListener==null" : "personActionsListener!=null");
        ButterKnife.bind(this);
        //初始化照相机
        mCropParams = new CropParams(this);
        /**
         * @see PersonPresenter#requestUserInfo()
         */
        personActionsListener.requestUserInfo();
        rxSubscription = RxBus
                .getDefault()
                .toObservable(InfoUpEvent.class)
                .subscribe(new Action1<InfoUpEvent>() {
                    @Override
                    public void call(InfoUpEvent infoUpEvent) {
                        KLog.i("TAG", "call - infoUpEvent" + infoUpEvent.getType() + "-" + infoUpEvent.getName());
                        switch (infoUpEvent.getType()) {
                            case InfoUpActivity.TYPE_01:
                                tvPersonName.setText(infoUpEvent.getName());
                                break;
                            case InfoUpActivity.TYPE_02:
                                tvPersonEmail.setText(infoUpEvent.getName());
                                break;
                            case InfoUpActivity.TYPE_03:
                                tvPersonQq.setText(infoUpEvent.getName());
                                break;
                        }


                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        KLog.i("TAG", "call - throwable");
                    }
                });

    }

    @OnClick(R.id.relative_person_avatar)
    public void relative_person_avatar(View view) {
        showPopupWindow();

    }

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;

    public void showPopupWindow() {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.camera_albums, null);

        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        final PopupWindow window = new PopupWindow(view,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        window.setFocusable(true);

        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x00000000);
        window.setBackgroundDrawable(dw);
        // 设置popWindow的显示和消失动画
        window.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        window.showAtLocation(findViewById(R.id.index_tv_title),
                Gravity.BOTTOM, 0, 0);

        view.findViewById(R.id.tv_camera).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub

                        //拍照
                        takePicture();
                        window.dismiss();

                    }
                });
        view.findViewById(R.id.tv_albums).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        //相册
                        openAlbum();
                        window.dismiss();

                    }
                });
        view.findViewById(R.id.tv_cancel).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        window.dismiss();
                    }
                });

    }


    // 拍照
    public void takePicture() {
        mCropParams.enable = true;
        mCropParams.compress = false;
        Intent intent = CropHelper.buildCameraIntent(mCropParams);
        startActivityForResult(intent, CropHelper.REQUEST_CAMERA);
    }

    // 打开本地相册
    public void openAlbum() {
        mCropParams.enable = true;
        mCropParams.compress = false;
        Intent intent = CropHelper.buildGalleryIntent(mCropParams);
        startActivityForResult(intent, CropHelper.REQUEST_CROP);
    }


    @Override
    public void onPhotoCropped(final Uri uri) {
        // Original or Cropped uri
        /*网络请求*/ //拍照 相册 从此处获取
        KLog.i("Evd", "onPhotoCropped" + uri.getPath());
        /**
         * @see PersonPresenter#updateAvatar(File)
         */
        personActionsListener.updateAvatar(new File(uri.getPath()));
    }

    @Override
    public void onCompressed(Uri uri) {
        // Compressed uri
        //        Log.i(TAG, "onCompressed: " + uri.getPath());


    }

    @Override
    public void onCancel() {
        Toast.makeText(this, "取消", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onFailed(String message) {
        Toast.makeText(this, "操作失败: " + message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void handleIntent(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
    }

    @Override
    public CropParams getCropParams() {
        return mCropParams;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        KLog.i("TAG", "-" + requestCode + "=" + resultCode);
        if (requestCode == CropHelper.REQUEST_CROP || requestCode == CropHelper.REQUEST_CAMERA) {
            CropHelper.handleResult(PersonActivity.this, requestCode, resultCode, data);
        }
    }

    @OnClick(R.id.relative_person_name)
    public void relative_person_name(View view) {
        startActivity(new Intent(this, InfoUpActivity.class)
                .putExtra("id_title", R.string.str_info_up_name)
                .putExtra("id_content", tvPersonName.getText().toString().trim())
                .putExtra("id_type", InfoUpActivity.TYPE_01));

    }

    @OnClick(R.id.relative_person_email)
    public void relative_person_email(View view) {
        startActivity(new Intent(this, InfoUpActivity.class)
                .putExtra("id_title", R.string.str_info_up_email)
                .putExtra("id_content", tvPersonEmail.getText().toString().trim())
                .putExtra("id_type", InfoUpActivity.TYPE_02));

    }

    @OnClick(R.id.relative_person_qq)
    public void relative_person_qq(View view) {
        startActivity(new Intent(this, InfoUpActivity.class)
                .putExtra("id_title", R.string.str_info_up_qq)
                .putExtra("id_content", tvPersonQq.getText().toString().trim())
                .putExtra("id_type", InfoUpActivity.TYPE_03));

    }

    @OnClick(R.id.relative_person_phone)
    public void relative_person_phone(View view) {


    }


    @OnClick(R.id.linear_person_exit)
    public void linear_person_exit(View view) {
        AppManager.getAppManager().finishAllActivity();
        SPUtil.putAndApply(this, "is_login", false);
        SPUtil.putAndApply(this, "userid", "");
        boolean is_p = (Boolean) SPUtil.get(this, "is_p", false);
//        SPUtil.putAndApply(this, "phone", "");
        if (!is_p) {
            SPUtil.putAndApply(this, "password", "");
        }
        SPUtil.putAndApply(this, "username", "");
        SPUtil.putAndApply(this, "real_name", "");
        SPUtil.putAndApply(this, "userpic", "");
        SPUtil.putAndApply(this, "email", "");
        SPUtil.putAndApply(this, "qq", "");
        SPUtil.putAndApply(this, "ali_pay_card", "");
        SPUtil.putAndApply(this, "bank_card", "");
        SPUtil.putAndApply(this, "bank_name", "");
        startActivity(new Intent(this, HomeMainActivity.class));
        AppManager.getAppManager().finishAllActivity();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);//解除绑定，官方文档只对fragment做了解绑
        if (!rxSubscription.isUnsubscribed()) {
            rxSubscription.unsubscribe();
        }
    }
}
